package com.itboye.jinpuyiyuan.activity.message;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.callback.IFooterCallBack;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.ALIInfoBean;
import com.itboye.jinpuyiyuan.bean.IllTagBean;
import com.itboye.jinpuyiyuan.bean.UserInfoBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.CircleImageView;
import com.itboye.jinpuyiyuan.widget.FlowLayout;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2018/1/15 0015.
 */

public class IllessInfoActivity extends BaseActivity implements Observer {
    //title

    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private static int ADDREMARK=15;
    private static int UPDATEREMARK=16;
    private  BranchAddressPresenter presenter,presenter1;
    private String userid;//阿里百川id
    private int illUid;//患者用户id
    private String uid;//医生自己的id
    private TextView name;
    private ImageView personIcon;
    private TextView creatRemarkTv;
    private FlowLayout addRemarkTag;

    private List<IllTagBean> tagList;
    private ArrayList<String> list;
    private LinearLayout parentWidth;
    private int width;// Flowlayout的子控件的宽度(标签控件宽度为父控件Flowlayout控件宽度的1/3)
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_illessinfo);
        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        tvTitle.setText("患者详情");

        userid=getIntent().getStringExtra("userId");
        uid= (String) SPUtils.get(getApplication(),null,Const.UID,"");
        illUid= Integer.parseInt((String) SPUtils.get(getApplication(),null,userid,""));
        presenter = new BranchAddressPresenter(this);
        presenter1= new BranchAddressPresenter(this);
        presenter.queryPersonInfo(userid);
        presenter1.queryRemark(illUid);
        presenter.getPersonInfo(illUid+"");
        list=new ArrayList<>(); //记录患者标签
        tagList=new ArrayList<>();//标签的集合
        Log.d("121212","oncreate");

    }

    public void initViewData(final ArrayList<String> list){
        if (list.size()>0){
            addRemarkTag.setVisibility(View.VISIBLE);
            creatRemarkTv.setVisibility(View.GONE);
            getDisplay();
            for (int i=0;i<list.size();i++){
                TextView textView = new TextView(IllessInfoActivity.this);
                LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(width
                        ,100);
                if ((i+1)%3==0){
                    params.bottomMargin=15;
                }else {
                    params.rightMargin=15;
                    params.bottomMargin=15;
                }
//            params.gravity= Gravity.CENTER;
                textView.setPadding(16,16,16,16);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setMaxLines(2);
                textView.setTag(i);

                textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.illessinfo_corner_blue));
                textView.setText(list.get(i));
                textView.setTextSize(13);
                textView.setTextColor(getResources().getColor(R.color.white));
                textView.setLayoutParams(params);
                textView.setGravity(Gravity.CENTER);
                final String content=list.get(i);
                final int id=tagList.get(i).getId();
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(IllessInfoActivity.this, ModifyRemarkActivity.class);
                        intent.putExtra("content",content);
                        intent.putExtra("tag_id",id);
                        intent.putExtra("list",list);
                        intent.putExtra("illId",illUid);
                        startActivityForResult(intent,IllessInfoActivity.UPDATEREMARK);
                    }
                });
                addRemarkTag.addView(textView);
            }
            Log.d("width",width+"");
            ImageView imageView = new ImageView(IllessInfoActivity.this);

            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                    ,ViewGroup.LayoutParams.WRAP_CONTENT);
//        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(120
//                ,120);
//        params.setMargins(50,0,0,0);
//        params.gravity=Gravity.CENTER_VERTICAL;

            imageView.setLayoutParams(params);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(IllessInfoActivity.this, AddRemarkActivity.class);
                    intent.putExtra("list",list);
                    intent.putExtra("illId",illUid);
                    startActivityForResult(intent,IllessInfoActivity.ADDREMARK);
                }
            });
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.tianjia_small_ill));
            addRemarkTag.addView(imageView);
        }else {
            creatRemarkTv.setVisibility(View.VISIBLE);
            addRemarkTag.setVisibility(View.GONE);
        }

    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("121212","onstart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("121212","onresume");
    }

    //计算获得标签的宽度为父容器的1/3
    public void getDisplay(){
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int windowWidth = metric.widthPixels;  // 屏幕宽度（像素）
        int windowHeight = metric.heightPixels;  // 屏幕高度（像素）
        float windowdDensity = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        int windowDensityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
        width= (int) ((windowWidth-20*windowdDensity-30)/3);
    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){

            case R.id.rlLeft:
            case R.id.leftImg:

                this.finish();
                break;
            case R.id.creatRemarkTv:
                Intent intent = new Intent(IllessInfoActivity.this, AddRemarkActivity.class);
                intent.putExtra("list",list);
                intent.putExtra("illId",illUid);
                startActivityForResult(intent,IllessInfoActivity.ADDREMARK);
                break;

        }
    }

    @Override
    public void update(Observable o, Object arg) {

        ResultEntity result = (ResultEntity) arg;
        if (result!=null){
            if (result.getEventType()== BranchAddressPresenter.By_Alibaichuan_info_success){
//                MAlert.alert("患者详情数据获取成功");
                ALIInfoBean bean= (ALIInfoBean) result.getData();
                name.setText(bean.getNick());

                Glide.with(IllessInfoActivity.this).load(bean.getIcon_url()).asBitmap().centerCrop().into(new BitmapImageViewTarget(personIcon) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        personIcon.setImageDrawable(circularBitmapDrawable);
                    }
                });
            }else if (result.getEventType()== BranchAddressPresenter.By_Alibaichuan_info_fail){
//                MAlert.alert("shibai");

            }else if (result.getEventType()== BranchAddressPresenter.By_UserTags_query_success){
//                MAlert.alert("查询标签成功");
                list.clear();
                tagList.clear();
                addRemarkTag.removeAllViews();
                tagList.addAll((List<IllTagBean>) result.getData()) ;
                for (int i=0;i<tagList.size();i++){
                    list.add(tagList.get(i).getTag_name());
                }
                initViewData(list);

            }else  if (result.getEventType()== BranchAddressPresenter.By_UserTags_query_fail){
//                MAlert.alert("查询标签失败");
                initViewData(list);
            }else if (result.getEventType()== BranchAddressPresenter.By_UserIdCard_info_success){//获取用户信息
                UserInfoBean userInfo= (UserInfoBean) result.getData();
//                String uid=userInfo.getUid();
                name.setText(userInfo.getNickname());

                Glide.with(IllessInfoActivity.this).load(Const.DoctorImg+userInfo.getUid()).asBitmap().centerCrop().into(new BitmapImageViewTarget(personIcon) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        personIcon.setImageDrawable(circularBitmapDrawable);
                    }
                });

            }else if (result.getEventType()== BranchAddressPresenter.By_UserIdCard_info_fail){//获取信息


            }
        }
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==IllessInfoActivity.ADDREMARK&&resultCode==AddRemarkActivity.ADDSUCCES){
            presenter1.queryRemark(illUid);
        }else if (requestCode==IllessInfoActivity.UPDATEREMARK&&resultCode==ModifyRemarkActivity.MOVEREMARK){
            presenter1.queryRemark(illUid);
        }
    }
}
